<!-- src/components/Calendar/views/WeekView.vue -->
<template>
  <div class="week-view">
    <!-- 周视图头部 -->
    <div class="week-header">
      <div class="time-column"></div>
      <div class="day-header-inWeek" v-for="day in weekDays" :key="day.date" 
           :class="{ active: day.date === selectedDay }">
        <div class="day-name-inWeek">{{ day.name }}</div>
        <div class="day-number-inWeek">{{ day.date }}</div>
        <div class="day-lunar-inWeek">{{ day.lunar }}</div>
      </div>
    </div>
    
    <!-- 时间网格 -->
    <div class="time-grid-wrapper">
      <div class="all-day-row">
        <div class="all-day-label">当天计划</div>
        <div class="all-day-columns">
          <div
            class="all-day-cell"
            v-for="(day, dayIndex) in weekDays"
            :key="`all-day-${dayIndex}`"
            @click.stop.prevent="handleAllDayAreaClick(day, $event)"
          >
            <template v-if="allDayButtonsByDay[dayIndex] && allDayButtonsByDay[dayIndex].length">
              <button
                v-for="buttonInfo in allDayButtonsByDay[dayIndex]"
                :key="buttonInfo.cardId || buttonInfo.tempKey"
                :class="[
                  'all-day-button',
                  {
                    'temp-button': buttonInfo.isTemp,
                    'all-day-button--task': buttonInfo.kind === 'task'
                  }
                ]"
                @click.stop.prevent="handleAllDayButtonClick(buttonInfo, day, $event)"
              >
                {{ buttonInfo.title }}
              </button>
            </template>
            <span v-else class="all-day-placeholder">暂无计划</span>
          </div>
        </div>
      </div>

      <div class="time-grid">
        <!-- 左侧时间段标签 -->
        <div class="time-labels">
          <div class="upperBlock-in-timeLabels"></div>
          <div class="time-label" v-for="hour in timeSlots" :key="hour">
            <span class="timeslot">{{ hour }}</span>
          </div>
        </div>
        
        <!-- 右侧时间网格 -->
        <div class="day-columns">
          <div class="day-column" v-for="(day, dayIndex) in weekDays" :key="dayIndex">
            <div 
              class="day-cell" 
              v-for="(hour, hourIndex) in timeSlots" 
              :key="hourIndex"
              @click.stop.prevent="handleCellClick(day, hourIndex, $event)"
            ></div>

            <!-- 当前时刻指示器 - 只在当前日期显示 -->
            <CurrentTimeIndicator
              :current-date="day.fullDate"
              :time-slots="timeSlots"
            />

            <!-- 时间段按钮 - 显示该日期和该时间段的卡片（模仿月视图的逻辑） -->
            <button
              v-for="cardButton in getCardButtonsForDay(day.fullDate, dayIndex)"
              :key="cardButton.cardId || cardButton.tempKey"
              :class="[
                'task-button',
                {
                  'temp-button': cardButton.isTemp,
                  'task-button--task': cardButton.kind === 'task',
                  'finished': cardButton.kind === 'task' && (cardButton.card as missionCard)?.isFinished
                }
              ]"
              :style="cardButton.style"
              @click.stop.prevent="handleTaskButtonClick(cardButton, $event)"
              @mousedown.stop
              @mouseup.stop
            >
              {{ cardButton.title }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 蒙板 -->
    <div 
      v-if="cardStore.showBaseCard || cardStore.showDetailCard" 
      class="overlay" 
      @click="handleOverlayClick"
    ></div>

    <!-- BaseCard 组件 -->
    <BaseCard
      v-if="cardStore.showBaseCard"
      :key="`basecard-${currentEditingCard?.id || 'new'}-${baseCardKey}`"
      :position="cardStore.adjustedBaseCardPosition()"
      :selected-date="cardStore.currentSelectedDate"
      :initial-all-day="baseCardDefaults.allDay"
      :initial-start-time="baseCardDefaults.startTime"
      :initial-end-time="baseCardDefaults.endTime"
      :edit-card-data="currentEditingCard"
      :creation-context="baseCardContext"
      @close="handleCloseBaseCard"
      @drag="handleBaseCardDrag"
      @save="handleSaveCard"
      @time-change="handleTimeChange"
    />

    <!-- 详情卡片组件 -->
    <div 
      v-if="cardStore.showDetailCard && cardStore.currentDetailCard"
      class="detail-card-container"
      :style="detailCardStyle"
    >
      <ActivityCard 
        v-if="cardStore.currentDetailCard.type === 'activity'" 
        :card-data="cardStore.currentDetailCard as any"
        :position="cardStore.adjustedDetailCardPosition()"
        @close="handleCloseDetailCard"
        @delete="handleDeleteActivityCard"
        @edit="handleEditActivityCard"
      />
      <MissionCard 
        v-else-if="cardStore.currentDetailCard.type === 'task'" 
        :card-data="cardStore.currentDetailCard as any"
        :position="cardStore.adjustedDetailCardPosition()"
        @close="handleCloseDetailCard"
        @delete="handleDeleteMissionCard"
        @edit="handleEditMissionCard"
      />
    </div>

    <!-- 编辑活动卡片组件 -->
    <EditACard
      v-if="showEditACard && editingACard"
      :card-data="editingACard"
      @close="handleEditACardClose"
      @update:cardData="handleACardUpdate"
      @delete="handleDeleteActivityCard"
    />

    <!-- 编辑任务卡片组件 -->
    <EditMCard
      v-if="showEditMCard && editingMCard"
      :card-data="editingMCard"
      @close="handleEditMCardClose"
      @update:cardData="handleMCardUpdate"
      @delete="handleDeleteMissionCard"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, nextTick } from 'vue'
import { useCardStore } from '@/store/card'
import type { DayData } from '@/types/timeData'
import type { activityCard, missionCard } from '@/types/card'
import BaseCard from '@/components/Cards/BaseCard.vue'
import ActivityCard from '@/components/Cards/ActivityCard.vue'
import MissionCard from '@/components/Cards/MissionCard.vue'
import CurrentTimeIndicator from '@/components/Calendar/CurrentTimeIndicator.vue'
import { ElMessage } from 'element-plus'
import EditACard from '@/components/Cards/EditACard.vue'
import EditMCard from '@/components/Cards/EditMCard.vue'

interface Props {
  selectedDate: Date
  weekDays: any[]
  timeSlots: string[]
}

const props = defineProps<Props>()
const emit = defineEmits(['choose-time-slot'])

type CalendarButtonKind = 'activity' | 'task' | 'temp'

interface CalendarCardButton {
  cardId?: string
  tempKey?: string
  title: string
  style: { top: string; height?: string; left?: string; width?: string; right?: string }
  isTemp: boolean
  card: activityCard | missionCard | null
  startIndex?: number
  endIndex?: number
  kind: CalendarButtonKind
}

const cardStore = useCardStore()

// 编辑卡片状态
const showEditACard = ref(false)
const editingACard = ref<activityCard | null>(null)
const showEditMCard = ref(false)
const editingMCard = ref<missionCard | null>(null)

// BaseCard 默认值（用于时间段）
const baseCardDefaults = reactive({ 
  allDay: false, 
  startTime: '00:00', 
  endTime: '01:00' 
})

const baseCardContext = ref<'grid' | 'allDay'>('grid')

// 当前编辑的卡片数据
const currentEditingCard = ref<activityCard | missionCard | null>(null)

// BaseCard 的 key，用于强制重新创建组件
const baseCardKey = ref(0)

interface AllDayButtonInfo {
  cardId?: string
  tempKey?: string
  title: string
  isTemp: boolean
  card: activityCard | missionCard | null
  kind: CalendarButtonKind
}

const normalizeDate = (date: Date) => {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate())
}

const isSameDate = (a: Date, b: Date) => a.getTime() === b.getTime()

const shouldTaskAppearInAllDayCell = (task: missionCard, cellDate: Date) => {
  const today = normalizeDate(new Date())
  const taskDate = normalizeDate(task.date)
  const targetCell = normalizeDate(cellDate)
  const isPastOrToday = taskDate.getTime() <= today.getTime()

  if (isPastOrToday) {
    return isSameDate(targetCell, today)
  }

  return isSameDate(targetCell, taskDate)
}

const GRID_HEIGHT = 60
const GRID_BORDER = 2
const GRID_TOTAL_HEIGHT = GRID_HEIGHT + GRID_BORDER

const clampHour = (hour: number) => Math.max(0, Math.min(23, hour))

const computeTopForDateTime = (date: Date) => {
  const hours = clampHour(date.getHours())
  const minutes = date.getMinutes()
  const gridTopBorder = hours * GRID_TOTAL_HEIGHT
  return gridTopBorder + 1 + minutes
}

const getMissionStartDate = (mission: missionCard) => {
  if (mission.beginTime) return new Date(mission.beginTime)
  if (mission.missionDate) return new Date(mission.missionDate)
  return new Date(mission.date)
}

// 计算详情卡片样式
const detailCardStyle = computed(() => {
  const position = cardStore.adjustedDetailCardPosition()
  return {
    left: `${position.x}px`,
    top: `${position.y}px`
  }
})

const selectedDay = computed(() => {
  return props.selectedDate.getDate()
})

const buildAllDayButtonsForDate = (date: Date): AllDayButtonInfo[] => {
  const buttons: AllDayButtonInfo[] = []
  const normalizedDate = normalizeDate(date)
  const dateString = normalizedDate.toDateString()

  let activityCards: activityCard[] = []
  if (typeof cardStore.getActivityCardsForDate === 'function') {
    activityCards = cardStore.getActivityCardsForDate(normalizedDate)
  } else {
    activityCards = cardStore.activityCards.filter(card => {
      const cardDateStr = new Date(card.startDate || card.date).toDateString()
      return cardDateStr === dateString
    })
  }

  // 根据显示状态过滤活动卡片
  if (!cardStore.showActivityCards) {
    activityCards = []
  }

  const allDayActivities = activityCards
    .filter(card => card.allDayLong)
    .sort((a, b) => {
      const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0
      const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0
      return timeB - timeA
    })

  allDayActivities.forEach(card => {
    buttons.push({
      cardId: card.id,
      title: card.title || '(无标题)',
      isTemp: false,
      card,
      kind: 'activity'
    })
  })

  let missionCardsForCell = cardStore.missionCards
    .filter(card => shouldTaskAppearInAllDayCell(card, normalizedDate))
    .filter(card => cardStore.shouldShowMissionCard(card))
    .sort((a, b) => {
      const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0
      const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0
      return timeB - timeA
    })

  missionCardsForCell.forEach(card => {
    buttons.push({
      cardId: card.id,
      title: card.title || '(无标题)',
      isTemp: false,
      card,
      kind: 'task'
    })
  })

  if (cardStore.tempButtonDate && baseCardDefaults.allDay) {
    const tempDate = normalizeDate(cardStore.tempButtonDate)
    if (isSameDate(normalizedDate, tempDate)) {
      buttons.push({
        tempKey: `temp-all-day-${tempDate.toDateString()}`,
        title: cardStore.getCardTitleForDate ? cardStore.getCardTitleForDate(tempDate) || '(无标题)' : '(无标题)',
        isTemp: true,
        card: null,
        kind: 'temp'
      })
    }
  }

  return buttons
}

const allDayButtonsByDay = computed(() => {
  return props.weekDays.map((day: any) => buildAllDayButtonsForDate(day.fullDate))
})

// 获取当前日期（如果当前日期在这一周中，返回当前日期，否则返回任意日期用于隐藏指示器）
const getCurrentDateInWeek = () => {
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  
  // 检查当前日期是否在这一周的某一天
  const isInWeek = props.weekDays.some(day => {
    const dayDate = new Date(day.fullDate.getFullYear(), day.fullDate.getMonth(), day.fullDate.getDate())
    return dayDate.getTime() === today.getTime()
  })
  
  // 如果当前日期在这一周，返回当前日期；否则返回一个未来的日期（确保指示器不显示）
  return isInWeek ? today : new Date(2100, 0, 1)
}

// 将小时索引转换为实际小时数
// 网格索引0代表00:00-01:00，索引1代表01:00-02:00，以此类推
// 每个网格严格对应一个小时，一小时只占住一个网格
// 索引对应的结束小时就是 index+1
// 例如：索引0 -> 结束小时1 (01:00)，索引1 -> 结束小时2 (02:00)
const mapIndexToHour = (index: number) => index + 1

// 将实际小时数转换为小时索引
// 一个网格对应一个小时，所以 hour 直接对应索引 hour
// 例如：hour=0 (00:xx) -> 索引0, hour=1 (01:xx) -> 索引1
const mapHourToIndex = (hour: number) => {
  // hour 直接作为索引：hour=0 -> 索引0, hour=1 -> 索引1
  return Math.max(0, Math.min(23, hour))
}

// 获取日期对应的时间范围（返回像素位置）
const getTimeRangeFromCard = (card: activityCard | missionCard): { startTop: number; endTop: number } | null => {
  if (card.type === 'activity') {
    const activity = card as activityCard
    if (activity.allDayLong) {
      // 全天事件，返回 null（不显示在时间段中，或显示全天标识）
      return null
    }
    if (activity.beginTime && activity.endTime) {
      const startDate = new Date(activity.beginTime)
      const endDate = new Date(activity.endTime)
      
      const startHour = startDate.getHours()
      const startMinute = startDate.getMinutes()
      const endHour = endDate.getHours()
      const endMinute = endDate.getMinutes()
      
      // 转换为网格索引
      // 网格索引直接对应时间段：索引0 -> 00:00-01:00, 索引1 -> 01:00-02:00, 以此类推
      // hour 直接作为网格索引
      const startIndex = startHour >= 0 && startHour < 24 ? startHour : -1
      const endIndex = endHour >= 0 && endHour <= 24 ? endHour : -1
      
      // 如果不在时间槽范围内，返回 null
      if (startIndex < 0 || endIndex < 0 || startIndex >= 24 || endIndex > 24) return null
      
      // 计算分钟偏移（按钮高度60px对应60分钟，1分钟 = 1px）
      // 分钟偏移值 = 分钟数
      const startMinuteOffset = startMinute
      const endMinuteOffset = endMinute
      
      // 计算像素位置：基于网格的绝对位置，确保按钮顶部对齐到网格线
      // 网格结构：每个 .day-cell 有 height: 60px 和 border: 1px solid #f0f0f0
      // 每个网格实际占用：1px(border-top) + 60px(height) + 1px(border-bottom) = 62px
      // 按钮的父容器是 .day-column，网格直接堆叠在其中
      // 第一个网格的顶部边框在 0px，内容区域从 1px 开始
      // 第二个网格的顶部边框在 62px，内容区域从 63px 开始
      const GRID_HEIGHT = 60 // 网格内容高度
      const GRID_BORDER = 2 // 每个网格的边框（top + bottom）
      const GRID_TOTAL_HEIGHT = GRID_HEIGHT + GRID_BORDER // 62px
      
      // 计算每个网格的顶部边框位置（网格线位置）
      // 网格0的顶部边框：0px
      // 网格1的顶部边框：62px
      // 网格2的顶部边框：124px
      const gridTopBorder = startIndex * GRID_TOTAL_HEIGHT
      const gridEndBorder = endIndex * GRID_TOTAL_HEIGHT
      
      // 按钮位置：网格顶部边框 + 1px(border) + 分钟偏移
      // 按钮高度60px，网格内容高度60px，完全匹配，无需居中偏移
      const startTop = gridTopBorder + 1 + startMinuteOffset
      const endTop = gridEndBorder + 1 + endMinuteOffset
      
      return {
        startTop,
        endTop
      }
    }
  }
  return null
}

// 检测两个时间段是否重叠
const isTimeRangeOverlap = (
  start1: number, end1: number,
  start2: number, end2: number
): boolean => {
  return !(end1 <= start2 || end2 <= start1)
}

// 获取某个日期在某个时间段的所有卡片按钮
const getCardButtonsForDay = (date: Date, dayIndex: number) => {
  const normalizedDate = normalizeDate(date)
  const dateString = normalizedDate.toDateString()

  const timedButtons: CalendarCardButton[] = []
  const taskPills: CalendarCardButton[] = []
  
  let activityCards = cardStore.activityCards.filter(card => {
    const cardDateStr = new Date(card.startDate || card.date).toDateString()
    return cardDateStr === dateString
  })
  
  // 根据显示状态过滤活动卡片
  if (!cardStore.showActivityCards) {
    activityCards = []
  }
  
  activityCards.forEach(card => {
    const timeRange = getTimeRangeFromCard(card)
    if (timeRange) {
      const startDate = new Date((card as activityCard).beginTime!)
      const endDate = new Date((card as activityCard).endTime!)
      const timeSpanMinutes = (endDate.getTime() - startDate.getTime()) / (1000 * 60)
      const height = Math.max(28, timeSpanMinutes)
      const startHour = startDate.getHours()
      const endHour = endDate.getHours()
      const startIndex = startHour >= 0 && startHour < 24 ? startHour : -1
      const endIndex = endHour >= 0 && endHour <= 24 ? endHour : -1

      timedButtons.push({
        cardId: card.id,
        title: card.title || '(无标题)',
        style: {
          top: `${timeRange.startTop}px`,
          height: `${height}px`
        },
        isTemp: false,
        card,
        startIndex,
        endIndex,
        kind: 'activity'
      })
    }
  })

  let missionCards = cardStore.missionCards.filter(card => {
    const cardDateStr = normalizeDate(card.date).toDateString()
    return cardDateStr === dateString
  })

  // 根据显示状态过滤任务卡片
  missionCards = missionCards.filter(card => cardStore.shouldShowMissionCard(card))

  missionCards.forEach(card => {
    const origin = card.originContext ?? 'grid'
    if (origin !== 'grid') {
      return
    }
    const startDate = getMissionStartDate(card)
    if (!startDate) return
    const top = computeTopForDateTime(startDate)
    const height = 28

    timedButtons.push({
      cardId: card.id,
      title: card.title || '(无标题)',
      style: {
        top: `${top}px`,
        height: `${height}px`,
        left: '4px',
        right: '4px'
      },
      isTemp: false,
      card,
      kind: 'task'
    })
  })
  
  if (cardStore.tempButtonDate && cardStore.tempButtonDate.toDateString() === dateString) {
    if (!baseCardDefaults.allDay && baseCardDefaults.startTime && baseCardDefaults.endTime) {
      const parseTimeToPosition = (timeStr: string) => {
        const parts = timeStr.split(':').map(Number)
        const hours = parts[0] ?? 0
        const minutes = parts[1] ?? 0
        const gridIndex = hours >= 0 && hours < 24 ? hours : -1
        if (gridIndex < 0) return null
        const gridTopBorder = gridIndex * GRID_TOTAL_HEIGHT
        return gridTopBorder + 1 + minutes
      }
    
      const startTop = parseTimeToPosition(baseCardDefaults.startTime)
      const endTop = parseTimeToPosition(baseCardDefaults.endTime)
      
      if (startTop !== null && endTop !== null) {
        const startParts = baseCardDefaults.startTime.split(':').map(Number)
        const endParts = baseCardDefaults.endTime.split(':').map(Number)
        const startHour = startParts[0] ?? 0
        const startMinute = startParts[1] ?? 0
        const endHour = endParts[0] ?? 0
        const endMinute = endParts[1] ?? 0
        const timeSpanMinutes = (endHour * 60 + endMinute) - (startHour * 60 + startMinute)
        const height = Math.max(28, timeSpanMinutes)
        const startIndex = startHour >= 0 && startHour < 24 ? startHour : -1
        const endIndex = endHour >= 0 && endHour < 24 ? endHour : -1
        
        timedButtons.push({
          tempKey: `temp-${dateString}`,
          title: cardStore.getCardTitleForDate(date) || '(无标题)',
          style: {
            top: `${startTop}px`,
            height: `${height}px`,
            left: '4px',
            right: '4px'
          },
          isTemp: true,
          card: null,
          startIndex,
          endIndex,
          kind: 'temp'
        })
      }
    }
  }

  if (timedButtons.length > 0) {
    timedButtons.sort((a, b) => {
      const topA = parseFloat(a.style.top) || 0
      const topB = parseFloat(b.style.top) || 0
      if (topA !== topB) return topA - topB
      const heightA = parseFloat(a.style.height || '0') || 0
      const heightB = parseFloat(b.style.height || '0') || 0
      return (topA + heightA) - (topB + heightB)
    })
    
    const groups: number[][] = []
    const processed = new Set<number>()
    
    for (let i = 0; i < timedButtons.length; i++) {
      if (processed.has(i)) continue
      
      const group = [i]
      processed.add(i)
      
      const buttonI = timedButtons[i]
      if (!buttonI) continue
      
      const topI = parseFloat(buttonI.style.top) || 0
      const heightI = parseFloat(buttonI.style.height || '0') || 0
      const bottomI = topI + heightI
      
      const toCheck = [i]
      while (toCheck.length > 0) {
        const currentIndex = toCheck.shift()
        if (currentIndex === undefined) break
        
        const buttonCurrent = timedButtons[currentIndex]
        if (!buttonCurrent) continue
        
        const topCurrent = parseFloat(buttonCurrent.style.top) || 0
        const heightCurrent = parseFloat(buttonCurrent.style.height || '0') || 0
        const bottomCurrent = topCurrent + heightCurrent
        
        for (let j = 0; j < timedButtons.length; j++) {
          if (j === currentIndex || processed.has(j)) continue
          
          const buttonJ = timedButtons[j]
          if (!buttonJ) continue
          
          const topJ = parseFloat(buttonJ.style.top) || 0
          const heightJ = parseFloat(buttonJ.style.height || '0') || 0
          const bottomJ = topJ + heightJ
          
          if (isTimeRangeOverlap(topCurrent, bottomCurrent, topJ, bottomJ)) {
            if (!group.includes(j)) {
              group.push(j)
              processed.add(j)
              toCheck.push(j)
            }
          }
        }
      }
      
      groups.push(group)
    }
    
    groups.forEach(group => {
      if (group.length === 1) {
        const buttonIndex = group[0]
        if (buttonIndex !== undefined) {
          const button = timedButtons[buttonIndex]
          if (button) {
            button.style.left = '2px'
            button.style.right = '2px'
            button.style.width = 'auto'
          }
        }
        return
      }
      
      const baseLeft = 2
      const baseRight = 2
      const gap = 1
      const totalGap = baseLeft + baseRight + (group.length - 1) * gap
      const buttonWidth = `calc((100% - ${totalGap}px) / ${group.length})`
      
      group.forEach((buttonIndex, index) => {
        const button = timedButtons[buttonIndex]
        if (!button) return
        
        if (index === 0) {
          button.style.left = `${baseLeft}px`
        } else {
          button.style.left = `calc(${baseLeft}px + ${index} * (${buttonWidth} + ${gap}px))`
        }
        button.style.width = buttonWidth
        button.style.right = 'auto'
      })
    })
  }
  
  return [...timedButtons, ...taskPills]
}

// 处理单元格点击
const handleCellClick = (day: DayData, hourIndex: number, event: MouseEvent) => {
  baseCardContext.value = 'grid'
  // 检查是否点击在按钮上，如果是则不处理
  const target = event.target as HTMLElement
  if (target && (target.closest('.task-button') || target.classList.contains('task-button'))) {
    return // 如果点击在按钮上，不处理单元格点击
  }
  
  emit('choose-time-slot', day, hourIndex, event)
  
  // 计算默认时间：点击的网格对应的时间段
  // 网格索引0对应00:00-01:00，索引1对应01:00-02:00，以此类推
  // 网格索引直接对应开始小时数，结束小时数是开始小时数+1
  const startHour = hourIndex
  const endHour = (hourIndex + 1) % 24
  
  let startStr = `${startHour.toString().padStart(2, '0')}:00`
  let endStr = `${endHour.toString().padStart(2, '0')}:00`

  const normalizedDate = normalizeDate(day.fullDate)
  
  // 确保关闭可能已打开的详情卡片和 BaseCard
  if (cardStore.showDetailCard) {
    cardStore.closeDetailCard()
  }
  if (cardStore.showBaseCard) {
    cardStore.closeBaseCard()
  }
  
  // 确保清空编辑数据，强制新建模式（必须在关闭卡片之后立即清空）
  currentEditingCard.value = null
  
  // 设置 BaseCard 默认值
  baseCardDefaults.allDay = false
  baseCardDefaults.startTime = startStr
  baseCardDefaults.endTime = endStr
  
  // 更新 key，强制 BaseCard 重新创建
  baseCardKey.value++
  
  // 打开 BaseCard（强制新建，因为同一天可以有多个不同时间段的卡片）
  if (target) {
    const rect = target.getBoundingClientRect()
    // 使用 nextTick 确保所有状态已更新
    nextTick(() => {
      cardStore.openBaseCard(normalizedDate, {
        x: rect.left,
        y: rect.bottom + 5
      }, true) // forceNew = true，允许同一天多个卡片
    })
  }
}

// 处理任务按钮点击
const handleTaskButtonClick = (buttonInfo: {
  cardId?: string
  tempKey?: string
  title: string
  isTemp: boolean
  card: activityCard | missionCard | null
}, event: MouseEvent) => {
  const target = event.currentTarget as HTMLElement
  if (target) {
    const rect = target.getBoundingClientRect()
    
    // 如果有关联的卡片，打开详情卡片（与月视图一致）
    if (buttonInfo.cardId && buttonInfo.card) {
      const card = buttonInfo.card
      
      // 先关闭可能已打开的卡片，确保状态清理
      if (cardStore.showBaseCard) {
        cardStore.closeBaseCard()
      }
      if (cardStore.showDetailCard) {
        cardStore.closeDetailCard()
      }
      
      // 打开详情卡片（显示模式，与月视图一致）
      cardStore.openDetailCard(card, {
        x: rect.left,
        y: rect.bottom + 5
      })
    } else {
      // 临时按钮或新建模式
      // 先关闭可能已打开的卡片
      if (cardStore.showBaseCard) {
        cardStore.closeBaseCard()
      }
      if (cardStore.showDetailCard) {
        cardStore.closeDetailCard()
      }
      
      currentEditingCard.value = null
      baseCardContext.value = 'grid'
      baseCardKey.value++
      
      nextTick(() => {
        cardStore.openBaseCard(props.selectedDate || new Date(), {
          x: rect.left,
          y: rect.bottom + 5
        }, true) // 新建模式，强制新建
      })
    }
  }
}

const openAllDayBaseCard = (day: DayData, referenceElement: HTMLElement) => {
  if (cardStore.showDetailCard) {
    cardStore.closeDetailCard()
  }
  if (cardStore.showBaseCard) {
    cardStore.closeBaseCard()
  }

  currentEditingCard.value = null
  baseCardDefaults.allDay = true
  baseCardDefaults.startTime = '00:00'
  baseCardDefaults.endTime = '23:45'
  baseCardContext.value = 'allDay'
  baseCardKey.value++

  const rect = referenceElement.getBoundingClientRect()
  nextTick(() => {
    const normalizedDate = normalizeDate(day.fullDate)
    cardStore.openBaseCard(normalizedDate, {
      x: rect.left,
      y: rect.bottom + 5
    }, true)
  })
}

const handleAllDayAreaClick = (day: DayData, event: MouseEvent) => {
  const target = event.currentTarget as HTMLElement
  if (!target) return
  openAllDayBaseCard(day, target)
}

const handleAllDayButtonClick = (buttonInfo: AllDayButtonInfo, day: DayData, event: MouseEvent) => {
  const target = event.currentTarget as HTMLElement
  if (!target) return
  const rect = target.getBoundingClientRect()

  if (buttonInfo.cardId && buttonInfo.card) {
    if (cardStore.showBaseCard) {
      cardStore.closeBaseCard()
    }
    if (cardStore.showDetailCard) {
      cardStore.closeDetailCard()
    }

    cardStore.openDetailCard(buttonInfo.card, {
      x: rect.left,
      y: rect.bottom + 5
    })
  } else if (buttonInfo.isTemp) {
    openAllDayBaseCard(day, target)
  }
}

// 检查是否是临时按钮
const isTempButton = (date: Date) => {
  return cardStore.tempButtonDate && cardStore.tempButtonDate.toDateString() === date.toDateString()
}

// 处理保存卡片
const handleSaveCard = async (cardData: activityCard | missionCard) => {
  try {
    if (cardData.type === 'activity') {
      await cardStore.saveACard(cardData)
    } else if (cardData.type === 'task') {
      await cardStore.saveMCard(cardData)
    }
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
    console.log('保存卡片失败', error)
  }
}

// 处理时间变化，同步更新临时按钮位置
const handleTimeChange = (timeData: { allDay: boolean; startTime: string; endTime: string; startDate: Date; endDate: Date }) => {
  // 更新 baseCardDefaults
  baseCardDefaults.allDay = timeData.allDay
  baseCardDefaults.startTime = timeData.startTime
  baseCardDefaults.endTime = timeData.endTime
  if (cardStore.tempButtonDate) {
    cardStore.updateTempButtonDate(timeData.startDate)
  }
}

// 处理蒙板点击
const handleOverlayClick = (event: MouseEvent) => {
  if (event.target === event.currentTarget) {
    handleCloseBaseCard()
    handleCloseDetailCard()
  }
}

// 关闭 BaseCard
const handleCloseBaseCard = () => {
  cardStore.closeBaseCard()
  currentEditingCard.value = null
}

// 关闭详情卡片
const handleCloseDetailCard = () => {
  cardStore.closeDetailCard()
}

// 删除ACard
const handleDeleteActivityCard = async (cardId: string) => {
  try {
    await cardStore.deleteACard(cardId)
    ElMessage.success(`活动卡片 ${cardId} 成功删除`)
    handleCloseDetailCard()

    if (editingACard.value && editingACard.value.id === cardId) {
      handleEditACardClose()
    }
  } catch(error) {
    console.log('删除活动卡片失败', error)
    ElMessage.error('删除活动卡片失败')
  }
  
}

// 编辑ACard
const handleEditActivityCard = (card: activityCard) => {
  ElMessage.info('编辑ACard')
  handleCloseDetailCard()
  editingACard.value = {...card} // 创建副本
  showEditACard.value = true
}

// 删除MCard
const handleDeleteMissionCard = async (cardId: string) => {
  try {
    await cardStore.deleteMCard(cardId)
    ElMessage.success(`任务卡片 ${cardId} 删除成功`)
    handleCloseDetailCard()

    if (editingMCard.value && editingMCard.value.id === cardId) {
      handleEditMCardClose()
    }
  } catch (error) {
    console.error('删除任务卡片失败:', error)
    ElMessage.error('删除任务卡片失败')
  }
}

// 编辑MCard
const handleEditMissionCard = (card: missionCard) => {
  handleCloseDetailCard()
  editingMCard.value = {...card} // 创建副本
  showEditMCard.value = true
  baseCardContext.value = card.originContext ?? 'grid'
}

// 处理 BaseCard 拖拽
const handleBaseCardDrag = (position: { x: number; y: number }) => {
  cardStore.updateBaseCardPosition(position)
}

// 处理EditACard关闭
const handleEditACardClose = () => {
  showEditACard.value = false
  editingACard.value = null
}

// 处理ACard更新
// 注意这里又更新又保存
const handleACardUpdate = async (updatedCard: activityCard) => {
  try {
    // 使用store的saveACard方法更新卡片
    await cardStore.saveACard(updatedCard)
    
    ElMessage.success('活动更新成功')
    
    // 关闭编辑卡片
    handleEditACardClose()
    
    // 如果需要，可以在这里添加其他逻辑，比如刷新卡片列表等
    
  } catch (error) {
    console.error('更新活动卡片失败:', error)
    ElMessage.error('更新活动卡片失败')
  }
}

// 处理EditMCard关闭
const handleEditMCardClose = () => {
  showEditMCard.value = false
  editingMCard.value = null
}

// 处理MCard更新
// 注意这里又更新又保存
const handleMCardUpdate = async (updatedCard: missionCard) => {
  try {
    // 使用store的saveMCard方法更新卡片（会自动同步到任务列表）
    const savedCard = await cardStore.saveMCard(updatedCard)
    
    // 如果当前显示的是详情卡片，更新详情卡片的数据
    if (cardStore.currentDetailCard && cardStore.currentDetailCard.id === savedCard.id) {
      cardStore.currentDetailCard = savedCard
    }
    
    ElMessage.success('任务更新成功')
    
    // 关闭编辑卡片
    handleEditMCardClose()
    
  } catch (error) {
    console.error('更新任务卡片失败:', error)
    ElMessage.error('更新任务卡片失败')
  }
}
</script>

<style scoped>
.week-view {
  height: 95%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.time-grid-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.all-day-row {
  display: flex;
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
  flex-shrink: 0;
}

.all-day-label {
  width: 80px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  border-right: 1px solid #e0e0e0;
}


.all-day-columns {
  display: flex;
  flex: 1;
}

.all-day-cell {
  flex: 1;
  border-right: 1px solid #f0f0f0;
  padding: 8px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  gap: 6px;
  min-height: 56px;
  cursor: pointer;
  background: #ffffff;
  text-align: center;
}

.all-day-cell:last-child {
  border-right: none;
}

.all-day-button {
  background: #2e7d32;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 4px 10px;
  font-size: 12px;
  cursor: pointer;
  transition: background 0.2s ease;
  white-space: nowrap;
}

.all-day-button:hover {
  background: #1b5e20;
}

.all-day-button--task {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.all-day-button--task::before {
  content: '\2713';
  font-weight: 600;
}

.all-day-placeholder {
  font-size: 12px;
  color: #999;
  pointer-events: none;
}

.week-header {
  display: flex;
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.time-column {
  width: 80px;
  padding: 16px 0px;
  border-right: 1px solid #e0e0e0;
}

.day-header-inWeek {
  flex: 1;
  padding: 16px 8px;
  text-align: center;
  border-right: 1px solid #e0e0e0;
}

.day-header-inWeek.active {
  background: #e3f2fd;
}

.day-name-inWeek {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.day-number-inWeek {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 2px;
}

.day-lunar-inWeek {
  font-size: 12px;
  color: #999;
}

.time-grid {
  flex: 1;
  overflow-y: auto;
  scrollbar-width: none;
  display: flex;
}

.time-labels {
  width: 80px;
  flex-shrink: 0;
  position: relative; /* 确保指示器定位正确 */
  overflow: visible; /* 允许指示器显示 */
}

.time-label {
  width: 60px;
  height: 60px;
  border-width: 1px 0;
  border-style: solid;
  border-color: transparent;
  flex-direction: column;
  padding-right: 8px;
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.timeslot {
  margin-top: auto;
}

.upperBlock-in-timeLabels {
  width: 60px;
  height: 7px;
}

.day-columns {
  display: flex;
  flex: 1;
}

.day-column {
  flex: 1;
  border-right: 1px solid #f0f0f0;
  position: relative;
  overflow: visible; /* 允许指示器显示 */
}

.day-cell {
  height: 60px;
  border: 1px solid #f0f0f0;
  cursor: pointer;
}

.day-cell:hover {
  background: #f8f9fa;
}

/* 任务按钮样式 - 与月视图一致的深绿色 */
.task-button {
  position: absolute;
  left: 2px;
  right: 2px; /* 默认情况下的样式，当有多个重叠按钮时会被 width 覆盖 */
  min-height: 28px; /* 减少2px */
  background: #2e7d32; /* 深绿色 */
  color: white;
  padding: 2px 6px; /* 减少2px */
  border-radius: 4px;
  font-size: 12px;
  text-align: center;
  border: none;
  cursor: pointer;
  transition: background 0.2s ease;
  z-index: 10;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  box-sizing: border-box; /* 确保 padding 包含在高度内，不影响对齐 */
}

.task-button--task {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  min-height: 24px;
  width: auto;
  right: auto;
  z-index: 20;
}

.task-button--task::before {
  content: '\2713';
  font-weight: 600;
}

.task-button.finished {
  background: #a5d6a7 !important; /* 更浅的绿色 */
  opacity: 0.7;
  text-decoration: line-through;
}

.task-button--task.finished::before {
  content: '✓';
  font-weight: 600;
  color: #4caf50;
}

.task-button:hover {
  background: #1b5e20; /* 更深的绿色 */
}

/* 临时按钮样式 - 与月视图一致 */
.temp-button {
  background: #ff9800; /* 橙色表示临时状态 */
}

.temp-button:hover {
  background: #f57c00; /* 更深的橙色 */
}

/* 蒙板样式 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: transparent;
  z-index: 999;
}

/* 详情卡片容器样式 */
.detail-card-container {
  position: fixed;
  width: 340px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e0e0e0;
  z-index: 1000;
}
</style>